package com.lcz.manage.sys.service.choose.factory;

import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.lcz.manage.sys.service.choose.ChooseBackService;
import com.lcz.manage.util.SpringContextUtils;

/**
 * @author lucz@yunrong.cn
 * @version V3.0
 * @date 2021/9/23 17:43
 */
@Component
public class ChooseBeanFactory {

    /**
     * 获取bean
     *
     * @param cls
     * @param back
     * @param <T>
     * @return
     */
    public <T> T getBean(Class<T> cls, boolean back) {
        Map<String, T> beanMap = SpringContextUtils.getBeansOfType(cls);
        if (CollectionUtils.isEmpty(beanMap)) {
            return null;
        }
        Set<Map.Entry<String, T>> entries = beanMap.entrySet();
        for (Map.Entry<String, T> entry : entries) {
            if (back) {
                if (ChooseBackService.class.isAssignableFrom(entry.getValue().getClass())) {
                    return entry.getValue();
                }
            }
            if (!back) {
                if (!ChooseBackService.class.isAssignableFrom(entry.getValue().getClass())) {
                    return entry.getValue();
                }
            }
        }
        return null;
    }
}
